/*
 *-------------------------------------------------------------
 *    copyrights by
 *    	Bartosz "Dust" Kowalski (dustization.info)
 *    	Maciej Krzysica 
 *-------------------------------------------------------------
 *    Plik: 	PCM.java
 */

package core;


import java.util.HashMap;
import java.util.Map;

import javax.swing.JFrame;

import core.PCMView.SettingsChangeListener;

/**
 * 		<p><b>PCM</b> - </p> 
 * 		<p></p> 
 * 
 * 		@author  <br><b>Bartosz 'Dust' Kowalski</b>
 */
public class PCM extends UnitAbstract
{
	private static final String	INPUT_NAME			= "IN";
	private static final String	PCM_NAME			= "PCM";
	private static final String	OUTPUT_NAME			= "OUT";
	
	private PCMView 						view		= new PCMView();
	private Map<PCMSettings, PCMOperation> 	operations 	= new HashMap<PCMSettings, PCMOperation>();
	
	private PCMSettings						settings;
	
	
	public PCM()
	{
		log("Creating PCM component...");
		
		inputs = new String[] { INPUT_NAME };
		outputs = new String[] { OUTPUT_NAME };
		
		log("adding settings change listeners...");
		
		view.addSettingsChangeListener(new SettingsChangeListener()
		{
			@Override
			public void onSettingsChanged(PCMSettings settings)
			{
				PCM.this.settings = settings; 
			}
		});
		
		log("registering algorithms...");
		
		// register algorithms
		registerOperation(PCMSettings.PCM_MODULATION_SETTINGS, new PCMModulation());
		registerOperation(PCMSettings.PCM_DEMODULATION_SETTINGS, new PCMDemodulation());
		registerOperation(PCMSettings.DPCM_MODULATION_SETTINGS, new PCMDifModulation());
		registerOperation(PCMSettings.DPCM_DEMODULATION_SETTINGS, new PCMDifDemodulation());
		
		log("all done!");
	}
	
	private void log(String log)
	{
		System.out.println(log);
	}
	
	private void registerOperation(PCMSettings settings, PCMOperation operation)
	{
		operations.put(settings, operation);
	}
	
	private PCMOperation getCurrentOperation()
	{
		return operations.get(settings);
	}
	
	/**
	 * 		@see core.Unit#read(core.DataPackage, java.lang.String)
	 */
	@Override
	public void read(DataPackage dataPack, String tPort)
	{
		if ( !tPort.equals(INPUT_NAME) )
			return;
			
		switch ( view.getComponentState() )
		{		
			// process data
			case POWER_ON_WORKING:
				PCMOperationData opData;
				PCMOperation operation = getCurrentOperation();
				
				opData = operation.operate(dataPack, settings);
				if ( !opData.getSendData() )
					break;
				else
					dataPack = opData.getData();
					
			// jsut send data
			case POWER_ON_STOPPED: 
				sendData(dataPack, OUTPUT_NAME);
				break;			
		}
	}
	
	
	
	/**
	 * 		@see core.Unit#getFrame()
	 */
	@Override
	public JFrame getFrame()
	{
		return view;
	}
	
	/**
	 * 
	 * 		@see java.lang.Object#toString()
	 */
	@Override
	public String toString()
	{
		return PCM_NAME;
	}
	
}
